//
//  resetPwdVC.m
//  UIScrollView的快速使用
//
//  Created by hongfei tam on 2019/3/6.
//  Copyright © 2019 YQ05. All rights reserved.
//

#import "resetPwdVC.h"
#import "MKConstant.h"
#import "network.h"
#import "LoginViewController3.h"

@interface resetPwdVC ()<UITextFieldDelegate>{
    NSString *titlestr;
    NSMutableDictionary *labelDic;
    
    UIActivityIndicatorView *loadActivity;  //加载动画
    UIView *activityBg;
    
    UITextField *activeField;
    LoginViewController3 *loginvc;
    // UILabel *titleLabel;
}
@property (weak, nonatomic) IBOutlet UIView *BGview;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UITextField *emailTF;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@end



@implementation resetPwdVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _BGview.backgroundColor = [UIColor whiteColor];
    _BGview.layer.shadowColor = [UIColor grayColor].CGColor;
    _BGview.layer.shadowOffset = CGSizeMake(3, 3);
    _BGview.layer.shadowOpacity = 0.8;
    ////  圆角效果
    _BGview.layer.cornerRadius = 2;
    _BGview.layer.borderColor = [UIColor grayColor].CGColor;
    _BGview.layer.borderWidth = 1;
    
    self.view.backgroundColor = BGGRAYCOLOR;
    
    //键盘遮挡
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(keyboardHide:)];
    
    tap.cancelsTouchesInView = NO;
    
    [self.view addGestureRecognizer:tap];
    
    //textField.delegate = self;
    
    titlestr = @"重置密碼";
    
    labelDic = [[NSMutableDictionary alloc]init];
//    [labelDic setValue:@"請輸入姓名" forKey:@"name"];
//    [labelDic setValue:@"請輸入聯絡電話" forKey:@"phone"];
    [labelDic setValue:@"請輸入電郵" forKey:@"email"];
//    [labelDic setValue:@"請輸入登入密碼" forKey:@"pwd1"];
//    [labelDic setValue:@"再次輸入登入密碼" forKey:@"pwd2"];
    [labelDic setValue:@"提交" forKey:@"submit"];
    //[labelDic setValue:@"已有賬戶？" forKey:@"account"];
    [labelDic setValue:@"返回登入" forKey:@"login"];
    
    // Do any additional setup after loading the view.
    [self settitleLabel];
    [self setemailTF];
    [self setsubmitBtn];
    [self setloginBtn];
    // Do any additional setup after loading the view.
    //接收網絡回傳信息
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginstatusAction:) name:@"resetpassstatus" object:nil];
}

-(void)settitleLabel{
    //  3 字体
    //UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, content.bounds.size.width, 50)];
    //label3.backgroundColor = MENUBROWN;// 背景色
    _titleLabel.text = titlestr;// 内容
    _titleLabel.textColor = MENUBROWN; //内容颜色
    //  使用字体名称
    //label3.font = [UIFont fontWithName:@"Aril-BoldMT" size:15.0];
    _titleLabel.font = [UIFont systemFontOfSize:26.0];
    //  对其方式: text内容 相对 uilabel command＋鼠标左键
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.numberOfLines = 1;
    
}

-(void)setemailTF{
    
    _emailTF.borderStyle = UITextBorderStyleLine;// 边框
    
    
    _emailTF.font = [UIFont systemFontOfSize:17.0];
    _emailTF.placeholder = [labelDic valueForKey:@"email"];// 提示
    
    _emailTF.keyboardType = UIKeyboardTypeEmailAddress;
    
    _emailTF.returnKeyType = UIReturnKeyDone;
    //设置UITextField的边框样式
    _emailTF.borderStyle = UITextBorderStyleRoundedRect;//圆角
    
    
    _emailTF.clearButtonMode = UITextFieldViewModeWhileEditing; //输入框右侧删除按钮  在UITextField文本框中开始编辑的时候显示清除设置，点击清除按钮删除内容
    _emailTF.delegate = self;// 谁来响应
}

-(void)setsubmitBtn{
    //   1 UI实例化 2 UI属性 3view 添加
    //initWithFrame:UI实例化 Frame
    //  UI+XX
    //UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake((content.bounds.size.width - 140)/2, 220, 140, 40)];
    
    //  作用：为Button 添加一个内容 1:title 2状态
    [_submitBtn setTitle:[labelDic valueForKey:@"submit"] forState:UIControlStateNormal];
    //  作用：为Button 内容设置颜色 1:title颜色 2状态
    [_submitBtn setTitleColor:MENUBROWN forState:UIControlStateNormal];
    
    [_submitBtn setBackgroundImage:[UIImage imageNamed:@"botton_140x40.jpg"] forState:UIControlStateNormal];
    
    //但是问题又出来，此时文字会紧贴到做边框，我们可以设置
    //button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    //使文字距离做边框保持10个像素的距离。
    //button.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 0);
    
    
    
    //  作用：是为button添加响应方法 1 self 2@selector(方法名) 3UIControlEventTouchUpInside:点击之后
    //  :
    [_submitBtn addTarget:self action:@selector(submitBtnAction) forControlEvents:UIControlEventTouchUpInside];
    //[content addSubview:button];
}
//  谁调用 bt 谁传递过来的
-(void)submitBtnAction{
    NSLog(@"submit？！");
    [self submitAction];
}




-(void)setloginBtn{
    //   1 UI实例化 2 UI属性 3view 添加
    //initWithFrame:UI实例化 Frame
    //  UI+XX
    //UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake((content.bounds.size.width - 140)/2, 220, 140, 40)];
    
    //  作用：为Button 添加一个内容 1:title 2状态
    [_loginBtn setTitle:[labelDic valueForKey:@"login"] forState:UIControlStateNormal];
    //  作用：为Button 内容设置颜色 1:title颜色 2状态
    [_loginBtn setTitleColor:MENUBROWN forState:UIControlStateNormal];
    _loginBtn.titleLabel.font = [UIFont systemFontOfSize: 20.0];  //字體大小
    //[_loginBtn setBackgroundImage:[UIImage imageNamed:@"botton_140x40.jpg"] forState:UIControlStateNormal];
    
    //但是问题又出来，此时文字会紧贴到做边框，我们可以设置
    //button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    //使文字距离做边框保持10个像素的距离。
    //button.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 0);
    
    
    
    //  作用：是为button添加响应方法 1 self 2@selector(方法名) 3UIControlEventTouchUpInside:点击之后
    //  :
    [_loginBtn addTarget:self action:@selector(loginBtnAction) forControlEvents:UIControlEventTouchUpInside];
    //[content addSubview:button];
}
//  谁调用 bt 谁传递过来的
-(void)loginBtnAction{
    if (loginvc == nil) {
        loginvc = [[LoginViewController3 alloc]init];
    }
    //[self.navigationController popToViewController:loginvc animated:YES];
    [self.navigationController popViewControllerAnimated:true];
    //    for (UIViewController *controller in self.navigationController.viewControllers) {
    //        if ([controller isKindOfClass:[LoginViewController3 class]]) {
    //            [self.navigationController popToViewController:controller animated:YES];
    //        }
    //    }
}


#pragma mark - 提交信息
////接收提交信息
//-(void)notifAction:(NSNotification*)notif{
//    NSDictionary *dic = notif.userInfo;
//    //    NSLog(@"s接受到的 字典。%@",dic);
//    //    NSString *string = [dic valueForKey:@"name"]; //pagetitle
//    //    NSLog(@"%@",string);
//    [self submitAction:dic];
//}
-(void)showAlert:(NSString *)title message:(NSString *)message{  //警告弹出框
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDestructive handler:nil];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:true completion:nil];
}
-(void)successAlert:(NSString *)title message:(NSString *)message{  //警告弹出框
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"重置密码成功 點擊OK");
        [self gotologinVC];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
    [alertController addAction:okAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:true completion:nil];
}

-(void)gotologinVC{
    dispatch_async(dispatch_get_main_queue(), ^{  //get 主线程
        //NSLog(@"currentThread %@ ",[NSThread currentThread]);
        //加载成功
        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:[LoginViewController3 class]]) {
                [self.navigationController popToViewController:controller animated:YES];
            }
        }
    });
    
}

-(void)submitAction{
    
    NSString *email = [_emailTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//    NSString *userphone = [_phoneTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//
//    NSString *userpass1 = [_pwd1TF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//    NSString *userpass2 = [_pwd2TF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    // 正则
    if ([email containsString:@"#"] || [email containsString:@"$" ] || [email containsString:@"%"]) {
        [self showAlert:@"警告！" message: @"包含非法字符！"];
    }else if (email.length<6){
        //NSLog(@"userpass %@",userpass);
        [self showAlert:@"警告！" message: @"郵箱长度不够！"];
    }else{
        [self loadingView];


        NSMutableDictionary *senddic = [[NSMutableDictionary alloc]init];
        [senddic setValue:email forKey:@"email"];
//        [senddic setValue:userpass1 forKey:@"userpass"];
        //[senddic setValue:useremail forKey:@"useremail"];


        //[self showAlert:@"发送消息" message: @"发送消息成功"];
        network *sendNetWork = [[network alloc]init];

        [sendNetWork POSTrequest:YOUNGURL type:@"resetpass" senddic:senddic savekey:@"resetpass"];  //发送数据

    }
    
}

-(void)loadingView{  //等待网络结果动画
    
    CGRect frame = CGRectMake(0, 0, 100, 100);
    //UIView *activityBg = [[UIView alloc]initWithFrame:frame];
    activityBg = [[UIView alloc]initWithFrame:frame];
    activityBg.center = self.view.center;
    activityBg.backgroundColor = [UIColor grayColor];
    activityBg.alpha = 0.7;
    activityBg.layer.cornerRadius = 5.0;
    [self.view addSubview:activityBg];
    
    //UIActivityIndicatorView *loadActivity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    
    loadActivity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    loadActivity.frame = CGRectMake(30, 30, 40, 40);
    [loadActivity sizeToFit];
    loadActivity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [activityBg addSubview:loadActivity];
    [loadActivity startAnimating];
}
-(void)stoploading{
    dispatch_async(dispatch_get_main_queue(), ^{  //get 主线程
        //NSLog(@"currentThread %@ ",[NSThread currentThread]);
        //加载成功
        [self->loadActivity stopAnimating];
        [self->activityBg removeFromSuperview];
    });
    
}

-(void)loginstatusAction:(NSNotification*)notif{
    [self stoploading];
    NSNumber *num = notif.object;
    int num2 = num.intValue;
    
    NSLog(@"返回狀態： %d",num2);
    
    if (num2 == 1) {
        
        dispatch_async(dispatch_get_main_queue(), ^{  //get 主线程
            //NSLog(@"currentThread %@ ",[NSThread currentThread]);
           [self successAlert:@"消息" message: @"重置成功"];
        });
    }else{
        NSDictionary *dic = notif.userInfo;
        //    NSString *statusnum1 = [dic valueForKey:@"loginstatus"];
        //    int statusnum = statusnum1.intValue;
        
        NSString *status = [dic valueForKey:@"status"];
        //NSLog(@"loginstatuslc222 %@",loginstatus);
        
        dispatch_queue_t q2 = dispatch_get_main_queue();  //get 主线程
        //    2 add Queue
        dispatch_async(q2, ^{
            //NSLog(@"currentThread %@ ",[NSThread currentThread]);
            
            [self showAlert:@"消息" message: status];
        });
    }
    
    
    
    
}


-(void)dealloc{
    
    //销毁的时候别忘移除监听
    //[self.webView.scrollView removeObserver:self forKeyPath:@"contentSize"];
    //接受信息 广播
    //[[NSNotificationCenter defaultCenter]removeObserver:self name:@"Promotionsend" object:nil];
    
    //接受信息 广播 发送成功信息
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"resetpassstatus" object:nil];
}

#pragma 键盘遮挡

// 点击done之后被调用
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    //NSLog(@"tag=%ld",(long)textField.tag);
    [textField resignFirstResponder];//取消当前键盘输入响应
    return true;
}

/**
 *   键盘遮挡
 */
-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [activeField resignFirstResponder];
//    [_pwd2TF resignFirstResponder];
//    [_pwd1TF resignFirstResponder];
}

-(void)viewWillAppear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    CGFloat kbHeight = [[aNotification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;//獲取鍵盤高度
    CGFloat offset0 = (activeField.frame.origin.y+activeField.frame.size.height) - (self.view.frame.size.height - kbHeight);//增加的高度
    double duration = [[aNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    if(offset0 > 0) {
        [UIView animateWithDuration:duration animations:^{
            self.view.frame = CGRectMake(0.0f, -offset0-10, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    activeField = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    activeField = nil;
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    double duration = [[aNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
